using hao_Model;
using hao_Dto.User;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using hao_Reppsitory;
using hao_Jwt;
using System;
using System.Security.Cryptography;
using System.Text;

namespace User.Service
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IJwtService _jwtService;

        public UserService(
            IUserRepository userRepository,
            IUserRoleRepository userRoleRepository,
            IRoleRepository roleRepository,
            IJwtService jwtService)
        {
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            _jwtService = jwtService;
        }

        public async Task<UserDto> GetByIdAsync(Guid id)
        {
            var user = await _userRepository.GetByIdAsync(id);
            return user == null ? null : ToDto(user);
        }

        public async Task<List<UserDto>> GetAllAsync()
        {
            var users = await _userRepository.GetAllAsync();
            return users.Select(ToDto).ToList();
        }

        public async Task AddAsync(UserDto userDto)
        {
            var user = ToEntity(userDto);
            await _userRepository.AddAsync(user);
        }

        public async Task UpdateAsync(UserDto userDto)
        {
            var user = ToEntity(userDto);
            await _userRepository.UpdateAsync(user);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _userRepository.DeleteAsync(id);
        }

        public async Task<List<RoleDto>> GetUserRolesAsync(Guid userId)
        {
            var userRoles = await _userRoleRepository.FindAsync(ur => ur.UserId == userId && !ur.IsDeleted);
            var roleIds = userRoles.Select(ur => ur.RoleId).ToList();
            var roles = await _roleRepository.GetAllAsync();
            return roles.Where(r => roleIds.Contains(r.Id)).Select(ToRoleDto).ToList();
        }

        public async Task AssignRolesAsync(Guid userId, List<Guid> roleIds)
        {
            var userRoles = await _userRoleRepository.FindAsync(ur => ur.UserId == userId && !ur.IsDeleted);
            foreach (var ur in userRoles)
            {
                await _userRoleRepository.DeleteAsync(ur.Id);
            }
            foreach (var roleId in roleIds)
            {
                var userRole = new UserRole
                {
                    Id = Guid.NewGuid(),  // 直接使用Guid.NewGuid()而不是ToString("N")
                    UserId = userId,
                    RoleId = roleId,
                    IsDeleted = false
                };
                await _userRoleRepository.AddAsync(userRole);
            }
        }

        public async Task<UserWithRolesDto> GetUserWithRolesAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null) return  null; // 重新抛出异常，让Controller层处理;
            var roles = await GetUserRolesAsync(userId);
            return new UserWithRolesDto
            {
                Id = user.Id,
                UserName = user.UserName,
                Roles = roles
            };
        }

        // 映射方法
        private UserDto ToDto(hao_Model.User user) => new UserDto
        {
            Id = user.Id,
            UserName = user.UserName,
            Nickname = user.Nickname,
            Avatar = user.Avatar,
            // 移除这两行
            // Level = user.Level,
            // LevelName = user.LevelName,
            Phone = user.Phone,
            Email = user.Email,
            Gender = user.Gender,
            Birthday = user.Birthday,
            RegisterTime = user.RegisterTime,
            LastLoginTime = user.LastLoginTime,
            Status = user.Status
        };

        private hao_Model.User ToEntity(UserDto dto) => new hao_Model.User
        {
            Id = dto.Id,
            UserName = dto.UserName,
            Nickname = dto.Nickname,
            Avatar = dto.Avatar,
            Phone = dto.Phone,
            Email = dto.Email,
            Gender = dto.Gender,
            Birthday = dto.Birthday,
            RegisterTime = dto.RegisterTime,
            LastLoginTime = dto.LastLoginTime,
            Status = dto.Status
        };

        private RoleDto ToRoleDto(hao_Model.Role role) => new RoleDto
        {
            Id = role.Id,
            Name = role.Name,
            Description = role.Description
        };

        /// <summary>
        /// 用户登录
        /// </summary>
        public async Task<LoginResponseDto> LoginAsync(LoginDto loginDto)
        {
            // 验证用户
            var user = await GetUserByUserNameAsync(loginDto.UserName);
            if (user == null)
            {
                throw new UnauthorizedAccessException("用户名或密码错误");
            }

            // 验证密码
            if (!VerifyPassword(loginDto.Password, await GetUserPasswordAsync(user.Id)))
            {
                throw new UnauthorizedAccessException("用户名或密码错误");
            }

            // 检查用户状态
            if (user.Status != 0)
            {
                throw new UnauthorizedAccessException("用户已被禁用");
            }

            // 获取用户角色
            var roles = await GetUserRolesAsync(user.Id);

            // 生成JWT Token
            var claims = new Dictionary<string, object>
            {
                { "UserId", user.Id },
                { "UserName", user.UserName },
                { "Roles", string.Join(",", roles.Select(r => r.Name)) }
            };

            var token = _jwtService.GenerateToken(claims);
            var expireTime = DateTime.Now.AddMinutes(60); // 根据配置设置

            // 更新最后登录时间
            await UpdateLastLoginTimeAsync(user.Id);

            return new LoginResponseDto
            {
                Token = token,
                ExpireTime = expireTime,
                User = user,
                Roles = roles
            };
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        public async Task<UserDto> RegisterAsync(RegisterDto registerDto)
        {
            // 检查用户名是否已存在
            var existingUser = await GetUserByUserNameAsync(registerDto.UserName);
            if (existingUser != null)
            {
                throw new InvalidOperationException("用户名已存在");
            }

            // 检查手机号是否已存在
            if (!string.IsNullOrEmpty(registerDto.Phone))
            {
                var phoneUser = await GetUserByPhoneAsync(registerDto.Phone);
                // 在UserService.cs的CreateUserAsync方法中
                if (phoneUser != null)
                {
                    throw new InvalidOperationException("手机号已存在");
                }
            }

            // 检查邮箱是否已存在
            if (!string.IsNullOrEmpty(registerDto.Email))
            {
                var emailUser = await GetUserByEmailAsync(registerDto.Email);
                if (emailUser != null)
                {
                    throw new InvalidOperationException("邮箱已被注册");
                }
            }

            // 创建新用户
            var user = new hao_Model.User
            {
                Id = Guid.NewGuid(),  // 直接使用Guid.NewGuid()而不是ToString()
                UserName = registerDto.UserName,
                Nickname = string.IsNullOrWhiteSpace(registerDto.Nickname) ? registerDto.UserName : registerDto.Nickname,
                Password = HashPassword(registerDto.Password),
                Phone = registerDto.Phone,
                Email = registerDto.Email,
                RegisterTime = DateTime.Now,
                Status = 0,
                IsDeleted = false
            };

            await _userRepository.AddAsync(user);
            return ToDto(user);
        }

        /// <summary>
        /// 验证用户凭据
        /// </summary>
        public async Task<bool> ValidateUserAsync(string userName, string password)
        {
            var user = await GetUserByUserNameAsync(userName);
            if (user == null || user.Status != 0)
            {
                return false;
            }

            var userPassword = await GetUserPasswordAsync(user.Id);
            return VerifyPassword(password, userPassword);
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        public async Task<UserDto> GetUserByUserNameAsync(string userName)
        {
            var users = await _userRepository.FindAsync(u =>
                (u.UserName == userName || u.Phone == userName || u.Email == userName)
                && !u.IsDeleted);
            var user = users.FirstOrDefault();
            return user != null ? ToDto(user) : null;
        }

        /// <summary>
        /// 更新最后登录时间
        /// </summary>
        public async Task UpdateLastLoginTimeAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.LastLoginTime = DateTime.Now;
                await _userRepository.UpdateAsync(user);
            }
        }

        // 私有辅助方法
        private async Task<string> GetUserPasswordAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.Password;
        }

        private async Task<UserDto> GetUserByPhoneAsync(string phone)
        {
            var users = await _userRepository.FindAsync(u => u.Phone == phone && !u.IsDeleted);
            var user = users.FirstOrDefault();
            return user != null ? ToDto(user) : null;
        }

        private async Task<UserDto> GetUserByEmailAsync(string email)
        {
            var users = await _userRepository.FindAsync(u => u.Email == email && !u.IsDeleted);
            var user = users.FirstOrDefault();
            return user != null ? ToDto(user) : null;
        }

        /// <summary>
        /// 密码哈希
        /// </summary>
        private string HashPassword(string password)
        {
            using (var sha256 = SHA256.Create())
            {
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password + "hao-cloud-salt"));
                return Convert.ToBase64String(hashedBytes);
            }
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        private bool VerifyPassword(string password, string hashedPassword)
        {
            var hashOfInput = HashPassword(password);
            return hashOfInput == hashedPassword;
        }

        // 在UserService类的末尾添加以下方法

        /// <summary>
        /// 根据ID获取用户（int类型ID）
        /// </summary>
        public async Task<UserDto> GetUserByIdAsync(Guid id)
        {
            return await GetByIdAsync(id);
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        public async Task<List<UserDto>> GetAllUsersAsync()
        {
            return await GetAllAsync();
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        public async Task<bool> UpdateUserAsync(Guid id, UpdateUserDto updateUserDto)
        {
            try
            {
                var existingUser = await _userRepository.GetByIdAsync(id);
                if (existingUser == null)
                {
                    return false;
                }

                // 更新用户信息
                existingUser.UserName = updateUserDto.UserName ?? existingUser.UserName;
                existingUser.Nickname = updateUserDto.Nickname ?? existingUser.Nickname;
                existingUser.Phone = updateUserDto.Phone ?? existingUser.Phone;
                existingUser.Email = updateUserDto.Email ?? existingUser.Email;
                existingUser.Avatar = updateUserDto.Avatar ?? existingUser.Avatar;
                existingUser.Gender = updateUserDto.Gender ?? existingUser.Gender;
                existingUser.Birthday = updateUserDto.Birthday ?? existingUser.Birthday;

                await _userRepository.UpdateAsync(existingUser);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除用户（int类型ID）
        /// </summary>
        public async Task<bool> DeleteUserAsync(Guid id)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(id);
                if (user == null)
                {
                    return false;
                }

                await DeleteAsync(id);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        public async Task<bool> ChangePasswordAsync(Guid userId, ChangePasswordDto changePasswordDto)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null)
                {
                    return false;
                }

                // 验证原密码
                if (!VerifyPassword(changePasswordDto.OldPassword, user.Password))
                {
                    return false;
                }

                // 更新新密码
                user.Password = HashPassword(changePasswordDto.NewPassword);
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        public async Task<LoginResponseDto> RefreshTokenAsync(Guid userId)
        {
            try
            {
                var user = await GetUserByIdAsync(userId);
                if (user == null || user.Status != 0)
                {
                    return null;
                }

                // 获取用户角色
                var roles = await GetUserRolesAsync(userId);

                // 生成新的JWT Token
                var claims = new Dictionary<string, object>
                {
                    { "UserId", user.Id },
                    { "UserName", user.UserName },
                    { "Roles", string.Join(",", roles.Select(r => r.Name)) }
                };

                var token = _jwtService.GenerateToken(claims);
                var expireTime = DateTime.Now.AddMinutes(60);

                return new LoginResponseDto
                {
                    Token = token,
                    ExpireTime = expireTime,
                    User = user,
                    Roles = roles
                };
            }
            catch
            {
             throw; // 重新抛出异常，让Controller层处理
            }
        }

        /// <summary>
        /// 启用用户
        /// </summary>
        public async Task<bool> EnableUserAsync(Guid userId, string reason = null)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null) return false;

                user.Status = (int)UserStatus.Normal;
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        public async Task<bool> DisableUserAsync(Guid userId, string reason = null)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null) return false;

                user.Status = (int)UserStatus.Disabled;
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 锁定用户
        /// </summary>
        public async Task<bool> LockUserAsync(Guid userId, string reason = null)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null) return false;

                user.Status = (int)UserStatus.Locked;
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 解锁用户
        /// </summary>
        public async Task<bool> UnlockUserAsync(Guid userId, string reason = null)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null) return false;

                user.Status = (int)UserStatus.Normal;
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 更新用户状态
        /// </summary>
        public async Task<bool> UpdateUserStatusAsync(Guid userId, UpdateUserStatusDto updateStatusDto)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId.ToString());
                if (user == null) return false;

                user.Status = updateStatusDto.Status;
                await _userRepository.UpdateAsync(user);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 批量启用用户
        /// </summary>
        public async Task<bool> BatchEnableUsersAsync(BatchOperationDto batchDto)
        {
            try
            {
                foreach (var userId in batchDto.UserIds)
                {
                    await EnableUserAsync(userId, batchDto.Reason);
                }
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 批量禁用用户
        /// </summary>
        public async Task<bool> BatchDisableUsersAsync(BatchOperationDto batchDto)
        {
            try
            {
                foreach (var userId in batchDto.UserIds)
                {
                    await DisableUserAsync(userId, batchDto.Reason);
                }
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        public async Task<bool> BatchDeleteUsersAsync(BatchOperationDto batchDto)
        {
            try
            {
                foreach (var userId in batchDto.UserIds)
                {
                    await DeleteUserAsync(userId);
                }
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 搜索用户（修正返回类型）
        /// </summary>
        public async Task<(List<UserDto> Users, int TotalCount)> SearchUsersAsync(UserSearchDto searchDto)
        {
            try
            {
                var users = await _userRepository.GetAllAsync();
                var query = users.Where(u => !u.IsDeleted);

                // 关键词搜索
                if (!string.IsNullOrEmpty(searchDto.Keyword))
                {
                    query = query.Where(u =>
                        u.UserName.Contains(searchDto.Keyword) ||
                        (u.Phone != null && u.Phone.Contains(searchDto.Keyword)) ||
                        (u.Email != null && u.Email.Contains(searchDto.Keyword)));
                }

                // 状态过滤
                if (searchDto.Status.HasValue)
                {
                    query = query.Where(u => u.Status == (int)searchDto.Status.Value);
                }

                // 性别过滤
                if (searchDto.Gender.HasValue)
                {
                    query = query.Where(u => u.Gender == searchDto.Gender.Value);
                }

               

                // 时间范围过滤
                if (searchDto.StartDate.HasValue)
                {
                    query = query.Where(u => u.RegisterTime >= searchDto.StartDate.Value);
                }
                if (searchDto.EndDate.HasValue)
                {
                    query = query.Where(u => u.RegisterTime <= searchDto.EndDate.Value);
                }

                var totalCount = query.Count();

                // 排序
                switch (searchDto.SortBy?.ToLower())
                {
                    case "username":
                        query = searchDto.SortDesc ?
                            query.OrderByDescending(u => u.UserName) :
                            query.OrderBy(u => u.UserName);
                        break;
                    case "registertime":
                        query = searchDto.SortDesc ?
                            query.OrderByDescending(u => u.RegisterTime) :
                            query.OrderBy(u => u.RegisterTime);
                        break;
                    default:
                        query = query.OrderByDescending(u => u.RegisterTime);
                        break;
                }

                // 分页
                if (searchDto.PageSize > 0)
                {
                    var skip = (searchDto.PageNumber - 1) * searchDto.PageSize;
                    query = query.Skip(skip).Take(searchDto.PageSize);
                }

                var result = query.Select(ToDto).ToList();
                return (result, totalCount);
            }
            catch
            {
                return (new List<UserDto>(), 0);
            }
        }

        /// <summary>
        /// 根据状态获取用户
        /// </summary>
        public async Task<List<UserDto>> GetUsersByStatusAsync(int status, int pageNumber = 1, int pageSize = 10)
        {
            try
            {
                var users = await _userRepository.GetAllAsync();
                var query = users.Where(u => !u.IsDeleted && u.Status == status);

                var skip = (pageNumber - 1) * pageSize;
                var result = query.Skip(skip).Take(pageSize).Select(ToDto).ToList();

                return result;
            }
            catch
            {
                return new List<UserDto>();
            }
        }

        /// <summary>
        /// 管理员创建用户
        /// </summary>
        public async Task<UserDto> CreateUserAsync(CreateUserDto createUserDto)
        {
            try
            {
                // 检查用户名是否已存在
                var existingUser = await GetUserByUserNameAsync(createUserDto.UserName);
                if (existingUser != null)
                {
                    throw new InvalidOperationException("用户名已存在");
                }

                // 检查手机号是否已存在
                if (!string.IsNullOrEmpty(createUserDto.Phone))
                {
                    var phoneUser = await GetUserByPhoneAsync(createUserDto.Phone);
                    if (phoneUser != null)
                    {
                        throw new InvalidOperationException("手机号已存在");
                    }
                }

                // 检查邮箱是否已存在
                if (!string.IsNullOrEmpty(createUserDto.Email))
                {
                    var emailUser = await GetUserByEmailAsync(createUserDto.Email);
                    if (emailUser != null)
                    {
                        throw new InvalidOperationException("邮箱已存在");
                    }
                }

                // 创建新用户
                var user = new hao_Model.User
                {
                    Id = Guid.NewGuid(),  // 直接使用Guid.NewGuid()而不是ToString()
                    UserName = createUserDto.UserName,
                    Nickname = string.IsNullOrWhiteSpace(createUserDto.Nickname) ? createUserDto.UserName : createUserDto.Nickname,
                    Password = HashPassword(createUserDto.Password),
                    Phone = createUserDto.Phone,
                    Email = createUserDto.Email,
                    Status = createUserDto.Status,
                    Gender = createUserDto.Gender,
                    RegisterTime = DateTime.Now,
                    IsDeleted = false
                };

                await _userRepository.AddAsync(user);

                // 分配角色（如果有）
                if (createUserDto.RoleIds != null && createUserDto.RoleIds.Any())
                {
                    foreach (var roleId in createUserDto.RoleIds)
                    {
                        var userRole = new UserRole
                        {
                            UserId = user.Id,
                            RoleId = roleId
                        };
                        await _userRoleRepository.AddAsync(userRole);
                    }
                }

                return ToDto(user);
            }
            catch
            {
               throw; // 重新抛出异常，让Controller层处理
            }
        }

        /// <summary>
        /// 管理员重置用户密码
        /// </summary>
        public async Task<bool> ResetUserPasswordAsync(Guid userId, string newPassword)
        {
            try
            {
                var user = await _userRepository.GetByIdAsync(userId);
                if (user == null || user.IsDeleted)
                {
                    return false;
                }

                // 加密新密码
                user.Password = HashPassword(newPassword);
                await _userRepository.UpdateAsync(user);
                
                return true;
            }
            catch
            {
                throw; // 重新抛出异常，让Controller层处理
            }
        }
    }
}